package com.youlu.campus.service.commission;

import com.google.common.collect.Lists;
import com.youlu.campus.base.exception.BusinessException;
import com.youlu.campus.entity.*;
import com.youlu.campus.entity.commission.*;
import com.youlu.campus.entity.commission.dto.CalCommissionDTO;
import com.youlu.campus.entity.commission.dto.DistributorApplyDTO;
import com.youlu.campus.entity.commission.dto.DistributorApplyQueryDTO;
import com.youlu.campus.entity.commission.dto.UpdateStatusDistributorApplyDTO;
import com.youlu.campus.entity.commission.vo.DistributorApplyVO;
import com.youlu.campus.entity.commission.vo.DistributorEntryVO;
import com.youlu.campus.entity.commission.vo.SharingCommissionCategoryItemVO;
import com.youlu.campus.entity.commission.vo.SharingCommissionDescVO;
import com.youlu.campus.entity.course.ActivityCourse;
import com.youlu.campus.entity.course.UserActivityCourse;
import com.youlu.campus.entity.course.UserCourseVideoStudy;
import com.youlu.campus.entity.dto.sms.SmsBaseInfoDTO;
import com.youlu.campus.entity.english.UserQuestionInfo;
import com.youlu.campus.service.activity.ActivityService;
import com.youlu.campus.service.ca.CaInfoService;
import com.youlu.campus.service.course.LiteHomeService;
import com.youlu.campus.service.course.UserCourseOrderService;
import com.youlu.campus.service.order.DigitalCaOrderDetailService;
import com.youlu.campus.service.order.OrderService;
import com.youlu.campus.service.sms.SmsServerService;
import com.youlu.campus.service.visitor.UserInfoExtendService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.repository.support.PageableExecutionUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Slf4j
@Service
public class DistributorApplyService {


    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private SmsServerService smsServerService;

    @Autowired
    private UserInfoExtendService userInfoExtendService;

    @Autowired
    private DistributionContentConfigService distributionContentConfigService;

    @Autowired
    private UserCourseOrderService userCourseOrderService;

    @Autowired
    private DigitalCaOrderDetailService digitalCaOrderDetailService;

    @Autowired
    private OrderService orderService;

    @Lazy
    @Autowired
    private ActivityService activityService;

    @Autowired
    private CaInfoService caInfoService;

    @Autowired
    private LiteHomeService liteHomeService;

    @Lazy
    @Autowired
    private DistributorGradeService distributorGradeService;

    private final static BigDecimal HUNDRED = BigDecimal.valueOf(100);

    @Autowired
    private DistributorAccountService distributorAccountService;


    /**
     * 清除根据活动ID分拥计算相关数据
     * @param activityId
     */
    public void deleteData(List<String> activityId){
        Query query = new Query();
        query.addCriteria(Criteria.where("activityId").in(activityId));
        //清除报名信息
        this.mongoTemplate.remove(query, UserParticipateActivityInfo.class);
        //清除邀请信息
        this.mongoTemplate.remove(query,UserInviteRecord.class);
        //清除答题相关信息
        this.mongoTemplate.remove(query,UserQaInfo.class);
        this.mongoTemplate.remove(query, UserQuestionInfo.class);
        //清除电子证书订单
        this.mongoTemplate.remove(query,DigitalCaOrder.class);

        //视频课程相关
        this.mongoTemplate.remove(query, UserCourseVideoStudy.class);
        this.mongoTemplate.remove(query, UserActivityCourse.class);



    }



    public SharingCommissionDescVO getDistributorSharingCommission(String userId, String activityId) {
        log.info("【分销赚钱tips】start DistributorApplyService.getDistributorSharingCommission userId:{}|activityId ",
                userId, activityId);
        SharingCommissionDescVO sharingCommissionDesc = new SharingCommissionDescVO();
        ActivityInfo activityInfo = activityService.findOne(activityId);
        if (Objects.isNull(activityInfo)) {
            return sharingCommissionDesc;
        }
        SharingCommissionInfo sharingCommissionInfo = activityInfo.getSharingCommissionInfo();
        if (Objects.isNull(sharingCommissionInfo) || !sharingCommissionInfo.getSharingProfit()) {
            return sharingCommissionDesc;
        }
        if (!sharingCommissionInfo.getShowCommissionIcon()) {
            return sharingCommissionDesc;
        }
        DistributorApply distributorApply = this.findByUserId(userId, DistributorApplyStatusEnum.PASS.getValue());
        if(Objects.nonNull(distributorApply)){
            sharingCommissionDesc.setDistributor(Boolean.TRUE);
        }
        sharingCommissionDesc.setShowCommissionIcon(Boolean.TRUE);
        String type = activityInfo.getType();
        List<SharingCommissionCategoryItemVO> itemList = Lists.newArrayList();
        switch (type) {
            case "wx-mini-dreambeat-contest":
                SharingCommissionCategoryItemVO chuSaiCommission = this.getChuSaiCommission(userId, activityInfo);
                SharingCommissionCategoryItemVO fuSaiCommission = this.getFuSaiCommission(userId, activityInfo);
                SharingCommissionCategoryItemVO jueSaiCommission = this.getJueSaiCommission(userId, activityInfo);
                if (Objects.nonNull(chuSaiCommission)) {
                    itemList.add(chuSaiCommission);
                }
                if (Objects.nonNull(fuSaiCommission)) {
                    itemList.add(fuSaiCommission);
                }
                if (Objects.nonNull(jueSaiCommission)) {
                    itemList.add(jueSaiCommission);
                }
                break;
            case "video":
            case "qimobang-video":
                SharingCommissionCategoryItemVO videoCommission = this.getViedoCommission(userId, activityInfo);
                if (Objects.nonNull(videoCommission)) {
                    itemList.add(videoCommission);
                }
                break;
            case "publicity":

                break;
        }
        SharingCommissionCategoryItemVO electronicCaCommission = this.getElectronicCaCommission(userId, activityInfo);
        SharingCommissionCategoryItemVO paperCaCommission = this.getPaperCaCommission(userId, activityInfo);
        if (Objects.nonNull(electronicCaCommission)) {
            itemList.add(electronicCaCommission);
        }
        if (Objects.nonNull(paperCaCommission)) {
            itemList.add(paperCaCommission);
        }
        sharingCommissionDesc.setSharingCommissionCategoryItem(itemList);
        return sharingCommissionDesc;
    }


    public DistributorEntryVO distributorEntry(String userId) {
        log.info("【分销者申请入口】start DistributorApplyService.distributorEntry userId:{}", userId);
        DistributorEntryVO distributorEntry = new DistributorEntryVO();
        DistributorApply distributorApply = this.findByUserId(userId, DistributorApplyStatusEnum.PASS.getValue());
        if (Objects.nonNull(distributorApply)) {
            distributorEntry.setJoinedDistributor(Boolean.TRUE);
            log.info("【分销者申请入口】DistributorApplyService.distributorEntry userId:{} 已申请通过", userId);
            return distributorEntry;
        }
        String bannerUrl = "";
        DistributionContentConfig distributionContentConfig = distributionContentConfigService.findOne();
        if (Objects.nonNull(distributionContentConfig)) {
            bannerUrl = distributionContentConfig.getBannerUrl();
        }
        //视频课程、竞赛证书
        Boolean userCourseOrderExist = userCourseOrderService.getBuyOrderByUserId(userId);
        if (userCourseOrderExist) {
            distributorEntry.setBannerUrl(bannerUrl);
            log.info("【分销者申请入口】DistributorApplyService.distributorEntry userId:{} 已购买视频课程或竞赛证书", userId);
            return distributorEntry;
        }
        //电子证书
        Boolean digitalCaOrderExist = digitalCaOrderDetailService.getBuyOrderByUserId(userId);
        if (digitalCaOrderExist) {
            log.info("【分销者申请入口】DistributorApplyService.distributorEntry userId:{} 已购买电子证书", userId);
            distributorEntry.setBannerUrl(bannerUrl);
            return distributorEntry;
        }
        //H5纸质证书
        Boolean h5OrderExist = orderService.getBuyOrderByUserId(userId);
        if (h5OrderExist) {
            log.info("【分销者申请入口】DistributorApplyService.distributorEntry userId:{} 已购买H5纸质证书", userId);
            distributorEntry.setBannerUrl(bannerUrl);
            return distributorEntry;
        }
        return distributorEntry;
    }

    public void updateStatus(UpdateStatusDistributorApplyDTO dto) {
        String optUserName = dto.getOptUserName();
        log.info("【分销者信息】修改状态 DistributorApplyService.updateStatus 操作人:{}| 修改状态:{}| 修改数据ID：{}", optUserName,
                dto.getStatus(), dto.getId());
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(dto.getId()));
        Update update = new Update();
        update.set("status", dto.getStatus());
        update.set("updatedTime", new Date());
        if (StringUtils.isNotBlank(dto.getRemark())) {
            update.set("remark", dto.getRemark());
        }
        update.set("auditorId", dto.getId());
        update.set("auditorName", optUserName);
        DistributorApply distributorApplyUpdate = new DistributorApply();
        distributorApplyUpdate.setRemark(dto.getRemark());
        distributorApplyUpdate.setStatus(dto.getStatus());
        distributorApplyUpdate.setApplyTime(LocalDateTime.now());
        distributorApplyUpdate.setAuditorId(dto.getOptUserId());
        distributorApplyUpdate.setAuditorName(dto.getOptUserName());
        update.push("applyLogList", distributorApplyUpdate.initApplyLog());
        this.mongoTemplate.updateFirst(query, update, DistributorApply.class);
    }

    public Page<DistributorApply> list(DistributorApplyQueryDTO dto) {
        Query query = new Query();
        String mobile = dto.getMobile();
        if (StringUtils.isNotBlank(mobile)) {
            query.addCriteria(Criteria.where("mobile").is(mobile));
        }
        String name = dto.getName();
        if (StringUtils.isNotBlank(name)) {
            Pattern pattern = Pattern.compile("^.*" + name + ".*$", Pattern.CASE_INSENSITIVE);
            query.addCriteria(Criteria.where("name").regex(pattern));
        }
        if (Objects.nonNull(dto.getStatus())) {
            query.addCriteria(Criteria.where("status").is(dto.getStatus()));
        }
        PageRequest pageRequest = PageRequest.of(dto.getPageNo() - 1, dto.getPageSize());
        long count = this.mongoTemplate.count(query, DistributorApply.class);
//        query.with(new Sort(Sort.Direction.DESC, "createdTime"));
        Sort sort=Sort.by(Sort.Direction.DESC, "createdTime");
        query.with(sort);
        List<DistributorApply> list = this.mongoTemplate.find(query.with(pageRequest), DistributorApply.class);
        if (CollectionUtils.isNotEmpty(list)) {
            list.stream().forEach(distributorApply -> {
                List<DistributorApply.ApplyLog> applyLogList = distributorApply.getApplyLogList().stream().sorted(Comparator.comparing(DistributorApply.ApplyLog::getOptTime).reversed()).collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(applyLogList)) {
                    if(applyLogList.size()>=2){
                        distributorApply.setPreStatus(applyLogList.get(1).getStatus());
                        distributorApply.setPreRemark(applyLogList.get(1).getRemark());
                    }
                }
                DistributorAccount distributorAccount = distributorAccountService.queryAccountByUserId(distributorApply.getUserId());
                if(Objects.nonNull(distributorAccount)){
                    distributorApply.setAmount(BigDecimal.valueOf(distributorAccount.getAccountBalance()).divide(BigDecimal.valueOf(100),2,BigDecimal.ROUND_HALF_UP).toString());
                }
            });
        }
        return PageableExecutionUtils.getPage(list, pageRequest, () -> count);
    }

    public DistributorApplyVO findByUserId(String userId) {
        log.info("【分销者信息】DistributorApplyService.findByUserId userId:{}", userId);
        DistributorApplyVO distributorApplyResult = new DistributorApplyVO();
        DistributionContentConfig distributionConfig = distributionContentConfigService.findOne();
        if (Objects.nonNull(distributionConfig)) {
            distributorApplyResult.setApplyDesc(distributionConfig.getApplyDesc());
            distributorApplyResult.setRuleDesc(distributionConfig.getRuleDesc());
        }
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        DistributorApply distributorApply = mongoTemplate.findOne(query, DistributorApply.class);
        if (Objects.nonNull(distributorApply)) {
            distributorApplyResult.setName(distributorApply.getName());
            distributorApplyResult.setStatus(distributorApply.getStatus());
            distributorApplyResult.setUniversityId(distributorApply.getUniversityId());
            distributorApplyResult.setUniversityName(distributorApply.getUniversityName());
            String mobile = distributorApply.getMobile();
            if (StringUtils.isNotBlank(mobile)) {
                distributorApplyResult.setMobile(mobile.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
            }
            if(DistributorApplyStatusEnum.NO_PASS.equals(distributorApply.getStatus())){
                distributorApplyResult.setStatus(DistributorApplyStatusEnum.APPLY.getValue());
            }
            return distributorApplyResult;
        }
        UserInfoExtend userInfoExtend = userInfoExtendService.findByUserId(userId);
        if (Objects.nonNull(userInfoExtend)) {
            distributorApplyResult.setName(userInfoExtend.getName());
            distributorApplyResult.setStatus(DistributorApplyStatusEnum.APPLY.getValue());
            distributorApplyResult.setUniversityId(userInfoExtend.getUniversityId());
            distributorApplyResult.setUniversityName(userInfoExtend.getUniversityName());
            String mobile = userInfoExtend.getMobile();
            if (StringUtils.isNotBlank(mobile)) {
                distributorApplyResult.setMobile(mobile.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
            }
            return distributorApplyResult;
        }
        distributorApplyResult.setStatus(DistributorApplyStatusEnum.APPLY.getValue());
        return distributorApplyResult;
    }


    /**
     * 分销者申请
     *
     * @param dto
     */
    public void apply(DistributorApplyDTO dto) {
        UserPO currentUser = dto.getCurrentUser();
        String userId = currentUser.getId();
        String mobile = dto.getMobile();
        String name = dto.getName();
        log.info("【分销者申请】DistributorApplyService.apply userId:{}| mobile:{}| name:{}", userId, mobile, name);
        DistributorApply distributorApply = findByUserId(userId, DistributorApplyStatusEnum.PASS.getValue());
        if (Objects.nonNull(distributorApply)) {
            log.warn("【分销者申请】DistributorApplyService.apply 重复申请  userId:{}| mobile:{}| name:{}", userId, mobile, name);
            throw new BusinessException("已通过申请分销者,请勿重新申请");
        }
        if (dto.getMustCode()) {
            SmsBaseInfoDTO smsDto = SmsBaseInfoDTO.builder().phone(mobile).code(dto.getCode()).build();
            Pair<Boolean, String> re = smsServerService.checkVerifyCode(smsDto);
            if (!re.getLeft()) {
                log.error("【分销者申请】DistributorApplyService.apply 手机验证码错误  userId:{}| mobile:{}| name:{}", userId, mobile,
                        name);
                throw new BusinessException(re.getRight());
            }
        }
        String universityId = dto.getUniversityId();
        String universityName = dto.getUniversityName();
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        Update update = new Update();
        update.set("name", name);
        UserInfoExtend userInfoExtend = userInfoExtendService.findByUserId(userId);
        if(Objects.nonNull(userInfoExtend)&&StringUtils.isNotBlank(userInfoExtend.getMobile())){
            update.set("mobile", userInfoExtend.getMobile());
        }else{
            update.set("mobile", mobile);
        }
        update.set("openId", currentUser.getOpenId());
        update.set("status", DistributorApplyStatusEnum.UNDER_REVIEW.getValue());
        LocalDateTime now = LocalDateTime.now();
        Date current = new Date();
        DistributorApply distributorApplyInner = new DistributorApply();
        distributorApplyInner.setApplyTime(LocalDateTime.now());
        distributorApplyInner.setStatus(DistributorApplyStatusEnum.UNDER_REVIEW.getValue());
        distributorApplyInner.setRemark("用户申请提交，待审核");
        update.push("applyLogList", distributorApplyInner.initApplyLog());
        update.set("applyTime", now);
        update.setOnInsert("createdTime", current);
        update.setOnInsert("updatedTime", current);
        if (StringUtils.isNotBlank(universityId)) {
            update.set("universityId", universityId);
        }
        if (StringUtils.isNotBlank(universityName)) {
            update.set("universityName", universityName);
        }
        FindAndModifyOptions findAndModifyOptions = new FindAndModifyOptions();
        findAndModifyOptions.upsert(Boolean.TRUE);
        findAndModifyOptions.returnNew(Boolean.TRUE);
        this.mongoTemplate.findAndModify(query, update, findAndModifyOptions, DistributorApply.class);
        //更新用户基本信息
        if (!StringUtils.isAllBlank(name, mobile)) {
            if (Objects.isNull(userInfoExtend) || StringUtils.isAnyBlank(userInfoExtend.getName(),
                    userInfoExtend.getMobile())) {
                currentUser.setName(name);
                currentUser.setMobile(mobile);
                currentUser.setH5SignUp(Boolean.TRUE);
                currentUser.setUniversityId(dto.getUniversityId());
                currentUser.setUniversityName(dto.getUniversityName());
                userInfoExtendService.saveOrUpdate(currentUser);
            }
        }
        log.info("【分销者申请】DistributorApplyService.apply 申请结束 userId:{}| mobile:{}| name:{}", userId, mobile, name);
    }

    public DistributorApply findByUserId(String userId, Integer status) {
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        query.addCriteria(Criteria.where("status").is(status));
        return mongoTemplate.findOne(query, DistributorApply.class);
    }

    /**
     * 决赛报名费
     *
     * @param userId
     * @param activityInfo
     * @return
     */
    private SharingCommissionCategoryItemVO getJueSaiCommission(String userId, ActivityInfo activityInfo) {
        Integer jueSaiFee = activityInfo.getJueSaiFee();
        if (Objects.isNull(jueSaiFee) || jueSaiFee <= 0) {
            return null;
        }
        SharingCommissionInfo sharingCommissionInfo = activityInfo.getSharingCommissionInfo();
        Double jueSaiSharingProfitRatio = sharingCommissionInfo.getJueSaiSharingProfitRatio();
        if(jueSaiSharingProfitRatio.compareTo(SharingCommissionInfo.ZERO)==0){
            return null;
        }
        BigDecimal jueSaiFeeBigDecimal = BigDecimal.valueOf(jueSaiFee);
        CalCommissionDTO calCommissionJueSaiFeeResult = distributorGradeService.doCalCommission(userId,
                jueSaiSharingProfitRatio, jueSaiFee);
        return SharingCommissionCategoryItemVO.builder().
                amount(jueSaiFeeBigDecimal.divide(HUNDRED, 2, BigDecimal.ROUND_HALF_UP).toString()).commissionCategory("决赛报名费").
                sharingCommissionRatio(calCommissionJueSaiFeeResult.getCurrentCommissionRatio().doubleValue()).
                sharingCommissionAmount(BigDecimal.valueOf(calCommissionJueSaiFeeResult.getSharingCommissionAmount()).divide(HUNDRED, 2, BigDecimal.ROUND_HALF_UP).toString()).build();
    }


    /**
     * 复赛报名费
     *
     * @param userId
     * @param activityInfo
     * @return
     */
    private SharingCommissionCategoryItemVO getFuSaiCommission(String userId, ActivityInfo activityInfo) {
        Integer fuSaiFee = activityInfo.getFuSaiFee();
        if (Objects.isNull(fuSaiFee) || fuSaiFee <= 0) {
            return null;
        }
        SharingCommissionInfo sharingCommissionInfo = activityInfo.getSharingCommissionInfo();
        Double fuSaiSharingProfitRatio = sharingCommissionInfo.getFuSaiSharingProfitRatio();
        if(fuSaiSharingProfitRatio.compareTo(SharingCommissionInfo.ZERO)==0){
            return null;
        }
        BigDecimal fuSaiFeeBigDecimal = BigDecimal.valueOf(fuSaiFee);
        CalCommissionDTO calCommissionFuSaiFeeResult = distributorGradeService.doCalCommission(userId,
                fuSaiSharingProfitRatio, fuSaiFee);
        return SharingCommissionCategoryItemVO.builder().
                amount(fuSaiFeeBigDecimal.divide(HUNDRED, 2, BigDecimal.ROUND_HALF_UP).toString()).commissionCategory("复赛报名费").
                sharingCommissionRatio(calCommissionFuSaiFeeResult.getCurrentCommissionRatio().doubleValue()).
                sharingCommissionAmount(BigDecimal.valueOf(calCommissionFuSaiFeeResult.getSharingCommissionAmount()).divide(HUNDRED, 2, BigDecimal.ROUND_HALF_UP).toString()).build();
    }

    /**
     * 初赛报名费
     *
     * @param userId
     * @param activityInfo
     * @return
     */
    private SharingCommissionCategoryItemVO getChuSaiCommission(String userId, ActivityInfo activityInfo) {
        Integer chuSaiFee = activityInfo.getChuSaiFee();
        if (Objects.isNull(chuSaiFee) || chuSaiFee <= 0) {
            return null;
        }
        SharingCommissionInfo sharingCommissionInfo = activityInfo.getSharingCommissionInfo();
        BigDecimal chuSaiFeeBigDecimal = BigDecimal.valueOf(chuSaiFee);
        Double chuSaiSharingProfitRatio = sharingCommissionInfo.getChuSaiSharingProfitRatio();
        if(chuSaiSharingProfitRatio.compareTo(SharingCommissionInfo.ZERO)==0){
            return null;
        }
        CalCommissionDTO calCommissionChuSaiFeeResult = distributorGradeService.doCalCommission(userId,
                chuSaiSharingProfitRatio, chuSaiFee);
        return SharingCommissionCategoryItemVO.builder().
                amount(chuSaiFeeBigDecimal.divide(HUNDRED, 2, BigDecimal.ROUND_HALF_UP).toString()).commissionCategory("初赛报名费").
                sharingCommissionRatio(calCommissionChuSaiFeeResult.getCurrentCommissionRatio().doubleValue()).
                sharingCommissionAmount(BigDecimal.valueOf(calCommissionChuSaiFeeResult.getSharingCommissionAmount()).divide(HUNDRED, 2, BigDecimal.ROUND_HALF_UP).toString()).build();
    }

    /**
     * 电子证书
     *
     * @param userId
     * @param activityInfo
     * @return
     */
    private SharingCommissionCategoryItemVO getElectronicCaCommission(String userId, ActivityInfo activityInfo) {
        SharingCommissionInfo sharingCommissionInfo = activityInfo.getSharingCommissionInfo();
        Integer contestDigitalCaFee = activityInfo.getContestDigitalCaFee();
        if (Objects.isNull(contestDigitalCaFee) || contestDigitalCaFee <= 0) {
            return null;
        }

        BigDecimal contestDigitalCaFeeBigDecimal = BigDecimal.valueOf(contestDigitalCaFee);
        Double digitalCaSharingProfitRatio = sharingCommissionInfo.getDigitalCaSharingProfitRatio();
        if(digitalCaSharingProfitRatio.compareTo(SharingCommissionInfo.ZERO)==0){
            return null;
        }
        CalCommissionDTO calCommissionContestDigitalCaResult = distributorGradeService.doCalCommission(userId,
                digitalCaSharingProfitRatio, contestDigitalCaFee);
        return SharingCommissionCategoryItemVO.builder().
                amount(contestDigitalCaFeeBigDecimal.divide(HUNDRED, 2, BigDecimal.ROUND_HALF_UP).toString()).commissionCategory("电子证书费").
                sharingCommissionRatio(calCommissionContestDigitalCaResult.getCurrentCommissionRatio().doubleValue()).
                sharingCommissionAmount(BigDecimal.valueOf(calCommissionContestDigitalCaResult.getSharingCommissionAmount()).divide(HUNDRED, 2, BigDecimal.ROUND_HALF_UP).toString()).build();
    }


    /***
     * 视频
     * @param userId
     * @param activityInfo
     * @return
     */
    private SharingCommissionCategoryItemVO getViedoCommission(String userId, ActivityInfo activityInfo) {
        SharingCommissionInfo sharingCommissionInfo = activityInfo.getSharingCommissionInfo();
        String courseId = activityInfo.getCourseId();
        if (StringUtils.isBlank(courseId)) {
            return null;
        }
        ActivityCourse activityCourse = liteHomeService.findByCourseId(courseId);
        if (Objects.isNull(activityCourse)) {
            return null;
        }
        Integer price = activityCourse.getPrice();
        if (Objects.isNull(price) || price == 0) {
            return null;
        }
        BigDecimal priceBigDecimal = BigDecimal.valueOf(price);
        Double videoOrderSharingProfitRatio = sharingCommissionInfo.getVideoOrderSharingProfitRatio();
        if(videoOrderSharingProfitRatio.compareTo(SharingCommissionInfo.ZERO)==0){
            return null;
        }
        CalCommissionDTO calCommissionVideoResult = distributorGradeService.doCalCommission(userId,
                videoOrderSharingProfitRatio, price);
        return SharingCommissionCategoryItemVO.builder().
                amount(priceBigDecimal.divide(HUNDRED, 2, BigDecimal.ROUND_HALF_UP).toString()).commissionCategory(
                "视频课程费").
                sharingCommissionRatio(calCommissionVideoResult.getCurrentCommissionRatio().doubleValue()).
                sharingCommissionAmount(BigDecimal.valueOf(calCommissionVideoResult.getSharingCommissionAmount()).divide(HUNDRED, 2, BigDecimal.ROUND_HALF_UP).toString()).build();

    }

    /**
     * 纸质证书
     *
     * @param userId
     * @param activityInfo
     * @return
     */
    private SharingCommissionCategoryItemVO getPaperCaCommission(String userId, ActivityInfo activityInfo) {
        SharingCommissionInfo sharingCommissionInfo = activityInfo.getSharingCommissionInfo();
        //是否有纸质
        Boolean hasPaperCa = activityInfo.getHasPaperCa();
        if (!hasPaperCa) {
            return null;

        }
        List<CaInfo> caInfoList = caInfoService.findByActivityId(activityInfo.getId());
        if (CollectionUtils.isEmpty(caInfoList)) {
            return null;
        }
        Double paperCaSharingProfitRatio = sharingCommissionInfo.getPaperCaSharingProfitRatio();
        if(paperCaSharingProfitRatio.compareTo(SharingCommissionInfo.ZERO)==0){
            return null;
        }
        int minPrice = caInfoList.stream().filter(caInfo -> caInfo.getPrice()>0).mapToInt(caInfo -> caInfo.getPrice()).min().orElse(0);
        int maxPrice = caInfoList.stream().filter(caInfo -> caInfo.getPrice()>0).mapToInt(caInfo -> caInfo.getPrice()).max().orElse(0);
        if(minPrice ==0 && maxPrice==0){
            return null;
        }
        CalCommissionDTO calCommissionMinResult = distributorGradeService.doCalCommission(userId, paperCaSharingProfitRatio, minPrice);
        if(minPrice == maxPrice){
            return SharingCommissionCategoryItemVO.builder().
                    commissionCategory("纸质证书费").
                    amount(BigDecimal.valueOf(minPrice).divide(HUNDRED, 2, BigDecimal.ROUND_HALF_UP).toString()).
                    sharingCommissionRatio(calCommissionMinResult.getCurrentCommissionRatio().doubleValue()).
                    sharingCommissionAmount(BigDecimal.valueOf(calCommissionMinResult.getSharingCommissionAmount()).divide(HUNDRED, 2, BigDecimal.ROUND_HALF_UP).toString()).build();
        }


        CalCommissionDTO calCommissionMaxResult = distributorGradeService.doCalCommission(userId,
                paperCaSharingProfitRatio, maxPrice);
        return SharingCommissionCategoryItemVO.builder().
                commissionCategory("纸质证书费").
                amount(BigDecimal.valueOf(minPrice).divide(HUNDRED, 2, BigDecimal.ROUND_HALF_UP) + "-" + BigDecimal.valueOf(maxPrice).divide(HUNDRED, 2, BigDecimal.ROUND_HALF_UP)).
                sharingCommissionRatio(calCommissionMaxResult.getCurrentCommissionRatio().doubleValue()).
                sharingCommissionAmount(BigDecimal.valueOf(calCommissionMinResult.getSharingCommissionAmount()).divide(HUNDRED, 2, BigDecimal.ROUND_HALF_UP).toString() +
                        "-" + BigDecimal.valueOf(calCommissionMaxResult.getSharingCommissionAmount()).divide(HUNDRED,
                        2, BigDecimal.ROUND_HALF_UP).toString()).build();
    }


}
